<template>
  <el-dialog ref="selectTaskFlowParams" title="流程参数" :visible.sync="params.visible" :close-on-click-modal="false" width="450px">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane v-if="showAgentParam" label="流程参数" name="tab1">
        <compTable
          ref="table"
          :show-search="false"
          :show-checkbox="false"
          :show-icon="true"
          :table-height="400"
          :table-header="tableHeader"
          :table-data="tableData"
          @cell-dblclick="CellDblClick"
          @click-events="handleRowClick"
        />
      </el-tab-pane>
      <el-tab-pane label="组件参数" name="tab2">
        <compTree
          ref="tree"
          :tree-show-checkbox="false"
          comp-tree-height="400"
          :show-search="false"
          :tree-default-expanded-keys="treeDefaultExpandedKeys"
          :tree-default-checked-keys="treeDefaultExpandedKeys"
          :tree-data="treeData"
        />
        <!-- :tree-node-select="treeNodeSelect" -->
      </el-tab-pane>
      <el-tab-pane label="流程参数组" name="tab3">
        <compTree
          ref="tree1"
          :tree-show-checkbox="true"
          comp-tree-height="400"
          :show-search="false"
          :tree-default-expanded-keys="treeDefaultExpandedKeys1"
          :tree-default-checked-keys="treeDefaultCheckedKeys1"
          :tree-data="treeData1"
          @treeNodeCheck="treeNodeCheck1"
        />
      </el-tab-pane>
    </el-tabs>
    <dialog-btn slot="footer">
      <el-checkbox v-show="showCheckbox" v-model="isSerialExec" style="float: left;">串行执行</el-checkbox>
    </dialog-btn>
  </el-dialog>
</template>
<script>
/** *************************************
 *      入参：params{
 *            flowData,
 *            flowID,
 *            isNewItem
 *      }
 *      出参：this.ok {
 *            g_flowPar
 *      }
 *
 * ********************************* */
import { getTaskFlowParam } from '@/api/flow'
import { CFlowChart } from '@/views/flow/flowEditor/flowchart'
export default {
  props: {
    params: { type: Object,
      default() {
        return {
          visible: false,
          flowData: '', // 入参
          folwID: '', // 入参
          isNewItem: '' // 入参
        }
      }
    }
  },
  data() {
    return {
      title: '',
      visible: false,
      activeName: 'tab1',
      formData: {},
      treeData: [], // 组件参数
      treeData1: [], // 流程参数组
      tableHeader: [
        { prop: 'name', label: '名称', isShow: true },
        { prop: 'value', label: '数据', isShow: true,
          render: (h, params) => {
            if (params.row.iType !== 1) {
              return h('el-input', {
                attrs: { value: params.row.value },
                class: 'input-deep',
                on: {
                  input: (e) => {
                    params.row.value = e
                  }
                  // blur: () => {
                  //   this.changeUser(params.row, params.index)
                  // }
                }
              })
            }
          }
        }
      ],
      tableData: [], // 流程参数
      isSerialExec: false, // el-checkbox选中状态
      showAgentParam: true, // 是否显示机器参数
      showCheckbox: false, // 是否显示串行执行
      selectRows: [], // 机器参数选中行
      checkedNodes: [], // 组件参数选中节点
      checkedNodes1: [], // 流程参数组选中节点
      treeDefaultExpandedKeys: [], // 组件参数默认选中的节点
      treeDefaultCheckedKeys1: [], // 流程参数组默认选中节点
      treeDefaultExpandedKeys1: [],
      g_flowPar: '' // 流程任务保存的数据
    }
  },
  mounted() {
    this.initWindow()
  },
  methods: {
    initWindow() {
      this.visible = true
      this.formData = this._.cloneDeep(this.params)
      this.g_flowPar = new this.ParamArr(this.Global.parseWebJson(this.formData.flowData))
      this.isSerialExec = this.g_flowPar.getBool('IsOneFlow')
      // 如果不是新建则保存已经设置的数据
      var vPar = new this.ParamArr()
      vPar.setStr('FlowID', this.formData.folwID)
      vPar.setBool('WebJson', true)
      getTaskFlowParam(vPar).then(vPar => {
        // 流程参数初始化
        this.initFlowParamTree(vPar)
        // 组件参数初始化
        this.initComponentParamTree(vPar)
        // 流程参数组
        this.initFlowParamArrTree(vPar)
        this.c
      }).finally(() => {
        this.$closeLoading()
      })
    },
    // 流程参数组初始化
    initFlowParamArrTree(vPar) {
      var table = new this.SQLTable(vPar.getTable('k_flow_param_group'))
      var nodes = []
      var nodeMap = new Map()
      table.first()
      while (!table.eof()) {
        var node = {}
        node.id = table.getValueByName('ID')
        node.pid = table.getValueByName('PID')
        node.flowId = table.getValueByName('FlowID')
        node.name = table.getValueByName('Name')
        node.text = node.name
        node.folder = 1
        nodeMap.set(node.id, node)
        var pNode = this.Global.getTreeviewPNode(nodeMap, nodes, node.pid)
        pNode.push(node)
        table.next()
      }
      table = new this.SQLTable(vPar.getTable('k_flow_param'))
      table.first()
      while (!table.eof()) {
        node = {}
        node.id = table.getValueByName('ID')
        node.pid = table.getValueByName('PID')
        node.flowId = table.getValueByName('FlowID')
        node.name = table.getValueByName('Name')
        node.text = node.name
        node.icon = 'wenbenmoban'
        nodeMap.set(node.id, node)
        pNode = this.Global.getTreeviewPNode(nodeMap, nodes, node.pid)
        pNode.push(node)
        table.next()
      }
      // 初始化勾选回显
      if (this.g_flowPar.has('FlowParamIDs')) {
        var ids = this.g_flowPar.getStr('FlowParamIDs').split(',')
        for (var i = 0; i < ids.length; i++) {
          this.treeDefaultCheckedKeys1.push(ids[i])
          this.treeDefaultExpandedKeys1.push(ids[i])
        }
        this.activeName = 'tab3'
        this.showCheckbox = true
      }
      this.treeData1 = nodes
    },
    // 流程参数初始化
    initFlowParamTree(vPar) {
      if (vPar.getBlobStr('Obj') === '') {
        return
      }
      var jsonData = this.Global.parseWebJson(vPar.getBlobStr('Obj'))
      if (jsonData === '') return
      var flowChart = new CFlowChart('', jsonData, '', '')
      var data = flowChart.data
      var nodes = []
      for (var i = 0; i < data.ParamCount; i++) {
        var node = this.getNodeByData(data, i, 3) // 流程参数
        nodes.push(node)
      }
      var tmpObj = this.Global.parseFlowNode(jsonData)
      this.getObjParams(tmpObj[0], nodes)
      this.tableData = nodes
    },
    getObjParams(paramArr, pNode, rootObj) {
      for (var i = 0; i < paramArr.length; i++) {
        if (!(paramArr[i] instanceof Object)) continue
        var paramObj = paramArr[i]
        var data = this.Global.parseWebJson(paramObj.Data)
        if ([6 /* 引用*/, 7].indexOf(data.ObjectType) !== -1) {
          var node = {}
          node.id = paramObj.ID
          node.nodes = []
          node.name = this.getObjText(paramObj)
          node.tags = ['']
          node.folder = 0 // 文件夹
          node.folder = true
          node.text = node.name
          node.icon = 'wenjianyi'
          var sParamArr = this.Global.getSubAndCiteObj(paramObj, rootObj)
          this.getObjParams(sParamArr, node.nodes, rootObj || paramArr[i])
          pNode.push(node)
        } else if (data.ParamCount > 0) {
          node = {}
          node.id = paramObj.ID
          node.name = this.getObjText(paramObj)
          node.tags = ['']
          node.nodes = []
          node.iType = 1 // 节点
          node.text = node.name
          node.icon = 'liuchen2'
          pNode.push(node)
          for (var j = 0; j < data.ParamCount; j++) {
            var cNode = this.getNodeByData(data, j, 2, node.id) // 节点参数
            node.nodes.push(cNode)
          }
        }
      }
    },
    // 获取节点参数
    getNodeByData(data, i, iType, pid) {
      var node = {}
      node.id = this.Global.getGuid()
      node.pid = pid
      node.name = data[this.Global.strFormat('Param{0}Name', i)]
      node.text = node.name
      node.icon = iType === 2 ? 'wenbenmoban' : 'wenbenbianji'
      if (iType === 2) {
        node.value = this.getFlowNodeValue(data, i, node.name, pid)
      } else {
        node.value = this.getValue(data, i, node.name)
      }
      node.isPassword = /(password|密码|pwd)/ig.test(node.name)
      node.tags = [node.isPassword ? '******' : node.value]
      node.iType = iType // 参数
      return node
    },
    // 获取流程节点text
    getObjText(obj) {
      var type = this.Global.parseWebJson(obj.Data).ObjectType
      var text = ''
      if (type === 2) {
        text = this.Global.strFormat('{0}.{1}[{2}]', obj.Text_TopLeft, obj.Text_ClientTop, obj.Text_ClientBottomt)
      } else if (type === 8) {
        text = this.Global.strFormat('{0}[{1}]', obj.Text_TopLeft, obj.Text_ClientBottom)
      } else {
        text = obj.Text_TopLeft
      }
      return text
    },
    // 获取流程节点里面的参数
    getFlowNodeValue(data, index, name, pid) {
      var res = ''
      if (this.g_flowPar.has(this.Global.strFormat('R_ParamsValue_{0}_{1}', pid, name))) {
        res = this.g_flowPar.getStr(this.Global.strFormat('R_ParamsValue_{0}_{1}', pid, name))
      } else {
        res = data[this.Global.strFormat('Param{0}Value', index)]
      }
      return res || ''
    },
    // 获取流程设计里面的参数
    getValue(data, index, name) {
      var res = ''
      if (!this.formData.isNewItem && this.g_flowPar.has(this.Global.strFormat('R_FlowParam_{0}', name))) {
        res = this.g_flowPar.getStr(this.Global.strFormat('R_FlowParam_{0}', name))
      } else {
        res = data[this.Global.strFormat('Param{0}Value', index)]
      }
      return res || ''
    },
    // 组件参数初始化
    initComponentParamTree(vPar) {
      var table = new this.SQLTable(vPar.getTable('k_flow_object_param_group'))
      var nodes = []
      var nodeMap = new Map()
      table.first()
      while (!table.eof()) {
        var node = {}
        node.id = table.getValueByName('ID')
        node.pid = table.getValueByName('PID')
        node.flowId = table.getValueByName('FlowID')
        node.name = table.getValueByName('Name')
        node.text = node.name
        node.folder = 1
        nodeMap.set(node.id, node)
        var pNode = this.Global.getTreeviewPNode(nodeMap, nodes, node.pid)
        pNode.push(node)
        table.next()
      }
      var cNodes = [] // 保存组件参数用于去除空目录
      // eslint-disable-next-line no-redeclare
      var table = new this.SQLTable(vPar.getTable('k_flow_object_param'))
      table.first()
      while (!table.eof()) {
        node = {}
        node.id = table.getValueByName('ID')
        node.pid = table.getValueByName('PID')
        node.flowId = table.getValueByName('FlowID')
        node.name = table.getValueByName('Name')
        node.text = node.name
        node.icon = 'wenbenmoban'
        nodeMap.set(node.id, node)
        pNode = this.Global.getTreeviewPNode(nodeMap, nodes, node.pid)
        pNode.push(node)
        cNodes.push(node)
        table.next()
      }
      for (var i = 0; i < cNodes.length; i++) {
        node = cNodes[i]
        while (node.pid) {
          pNode = nodeMap.get(node.pid)
          if (!pNode) break
          pNode.isShow = true
          node = pNode
        }
      }
      // 初始化展开
      if (this.g_flowPar.has('FlowVCLParamID')) {
        var sID = this.g_flowPar.getStr('FlowVCLParamID')
        this.treeDefaultExpandedKeys.push(sID)
        this.$refs.tree.setSelect(sID)
        this.activeName = 'tab2'
      }
      nodes = this.hiddenGroupNodeByisShow(nodes) // 隐藏空目录
      this.treeData = nodes
    },
    // 隐藏空目录
    hiddenGroupNodeByisShow(nodes) {
      nodes = nodes.filter(item => {
        return !(item.folder && !item.isShow)
      })
      for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i]
        if (node.nodes instanceof Array) {
          node.nodes = this.hiddenGroupNodeByisShow(node.nodes)
        }
      }
      return nodes
    },
    // 标签判断
    handleClick(tab) {
      if (this.activeName === 'tab3') this.showCheckbox = true
      else this.showCheckbox = false
    },
    // treeNodeSelect(node) {
    //   this.checkedNodes = node
    // },
    treeNodeCheck1(a, b) {
      this.checkedNodes1 = b.checkedNodes
    },
    // 获取流程参数选中行
    handleRowClick(rows) {
      // this.selectRows = rows
    },
    // 当checkbox选中状态时触发的事件
    // checkChange(isCheck) {
    //   this.isSerialExec = isCheck
    // },
    // 表格单元格双击事件
    CellDblClick(row, column) {
      if (column.property === 'value' && row.iType !== 1) {
        this.tableHeader[1].isEdit = !this.tableHeader[1].isEdit
      }
    },
    // 选中流程参数标签页 数据保存处理
    rstObjParamsPar(vPar) {
      var paramsIDs = []
      var paramNames = []
      const nodes = this.tableData
      for (var i = 0; i < nodes.length; i++) {
        const node = nodes[i]
        if (node.iType === 1) { // 组件节点
          paramsIDs.push(node.id)
          var names = []
          var cNodes = node.nodes || [] // 组件下的参数节点
          for (var j = 0; j < cNodes.length; j++) {
            var item = cNodes[j]
            names.push(item.name)
            vPar.setStr(this.Global.strFormat('R_ParamsValue_{0}_{1}', node.id, item.name), item.value)
          }
          vPar.setStrList(this.Global.strFormat('R_ParamsNames_{0}', node.id), names)
        } else if (node.iType === 3) {
          var name = node.name
          paramNames.push(name)
          vPar.setStr(this.Global.strFormat('R_FlowParam_{0}', name), node.value)
        }
      }
      vPar.setStrList('R_ParamsIDs', paramsIDs)
      vPar.setStrList('R_FlowParam', paramNames)
    },
    confirm() {
      var ids = []
      this.g_flowPar.remove('FlowVCLParamID')
      this.g_flowPar.remove('R_ParamsIDs')
      this.g_flowPar.remove('R_FlowParam')
      this.g_flowPar.remove('FlowParamIDs')
      this.g_flowPar.remove('IsOneFlow')
      if (this.activeName === 'tab1') {
        this.rstObjParamsPar(this.g_flowPar)
      } else if (this.activeName === 'tab2') {
        if (this.$refs.tree.getCurrentNode().length === 0 || this.$refs.tree.getCurrentNode().folder === 1) {
          this.$message.warning('请选择组件参数')
          return
        }
        this.g_flowPar.setStr('FlowVCLParamID', this.$refs.tree.getCurrentNode().id)
      } else if (this.activeName === 'tab3') {
        for (let i = 0; i < this.checkedNodes1.length; i++) {
          if (!this.checkedNodes1[i].folder) {
            ids.push(this.checkedNodes1[i].id)
          }
        }
        this.g_flowPar.setStr('FlowParamIDs', ids.join(','))
        this.g_flowPar.setBool('IsOneFlow', this.isSerialExec)
      }
      this.params.confirm({ g_flowPar: this.g_flowPar })
      Object.assign(this.$data, this.$options.data())
    }
  }
}
</script>
